package com.magicsoft.share.ui.share;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.magicsoft.share.R;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.share.Article;
import com.magicsoft.share.customview.dialog.DialogShare;
import com.magicsoft.share.presenter.share.ArticlePresenter;
import com.magicsoft.share.utils.DensityUtils;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.utils.WxShareUtil;
import com.magicsoft.share.view.share.IArticleView;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;

public class ArticleActivity extends BaseActivity<IArticleView, ArticlePresenter> implements IArticleView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.iv_title_head)
    RoundedImageView ivTitleHead;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    @BindView(R.id.view_title)
    View viewTitle;
    @BindView(R.id.tv_like)
    TextView tvLike;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.layout_bottom)
    LinearLayout layoutBottom;
    @BindView(R.id.view_bottom)
    View viewBottom;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.iv_like)
    ImageView ivLike;
    @BindView(R.id.layout_like)
    LinearLayout layoutLike;
    @BindView(R.id.iv_follow)
    ImageView ivFollow;
    @BindView(R.id.tv_follow)
    TextView tvFollow;
    @BindView(R.id.layout_follow)
    LinearLayout layoutFollow;
    private AgentWeb mAgentWeb;

    private PopupWindow mPopTop;

    private DialogShare mDialogShare ;

    private boolean isThumbsUp;
    private TextView tv_collection;
    private long articleId;
    private Article mArticle;

    private String mShareUrl ;
    private String mArticalTitle ;
    private String mShareImage ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    }

    @Override
    public ArticlePresenter initPresenter() {
        return new ArticlePresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_article;
    }

    @Override
    public void initData() {


        int articleId1 = getIntent().getIntExtra("articleId", -1);
        articleId=articleId1;

    }

    @Override
    public void initView() {
        initMyPop();
        initDialog();
    }

    @Override
    public void requestData() {


        mPresenter.getArticleDetail(articleId);

    }


    @OnClick({R.id.ibtn_left, R.id.ibtn_right, R.id.layout_like, R.id.tv_share, R.id.tv_comment, R.id.iv_title_head, R.id.layout_follow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                finish();
                break;
            case R.id.ibtn_right:

                Log.e("lyf", "onViewClicked: ");

                mPopTop.showAsDropDown(ibtnRight, 0, DensityUtils.dp2px(this, 10));

                break;
            case R.id.layout_like:
                setResult(RESULT_OK);
                if (isThumbsUp) {

                    mPresenter.deleteArticleLove(mArticle.getArticleId());
                } else {
                    mPresenter.articleLove(mArticle.getArticleId());
                }
                break;

            case R.id.layout_follow:
                setResult(RESULT_OK);
                if (tvFollow.getText().toString().equals("关注")) {
                    mPresenter.addFollow(mArticle.getAuthorId());
                } else {
                    mPresenter.deleteFollow(mArticle.getAuthorId());
                }
                break;
            case R.id.tv_share:
                mDialogShare.show(getSupportFragmentManager(), "");
                break;
            case R.id.tv_comment:
                Intent intent = new Intent(this, CommentListActivity.class);
                intent.putExtra("articleId", articleId);
                startActivity(intent);
                break;
            case R.id.iv_title_head:
                Intent intent1 = new Intent(this, HomePageActivity.class);
                intent1.putExtra("appUserId", mArticle.getAuthorId());
                startActivity(intent1);
                break;
            default:
                break;
        }
    }

    private void initMyPop() {
        mPopTop = new PopupWindow(this);
        mPopTop.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopTop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopTop.setFocusable(true);////获取焦点
        mPopTop.setTouchable(true);
        mPopTop.setOutsideTouchable(true);//设置popupwindow外部可点击
        //    mPopTop.update();// 刷新状态
        ColorDrawable dw = new ColorDrawable(0000000000);// 实例化一个ColorDrawable颜色为半透明
        mPopTop.setBackgroundDrawable(dw);// 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        mPopTop.setAnimationStyle(R.style.QQPopAnim);//设置显示和消失动画
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View conentView = inflater.inflate(R.layout.layout_right_pop, null);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv1:
                        Intent intent1 = new Intent(ArticleActivity.this, HomePageActivity.class);
                        intent1.putExtra("appUserId", mArticle.getAuthorId());
                        startActivity(intent1);
                        break;
                    case R.id.tv2:
                        mDialogShare.show(getSupportFragmentManager(), "");
                        break;
                    case R.id.tv3:
                        if (tv_collection.getText().toString().equals("收藏")) {
                            mPresenter.articleCollection(articleId);
                        } else {
                            mPresenter.deleteCollection(articleId);
                        }

                        break;
                    case R.id.tv4:
                        Intent intent = new Intent(ArticleActivity.this, ReportActivity.class);
                        intent.putExtra("articleId", String.valueOf(mArticle.getArticleId()));
                        intent.putExtra("articleTitle", mArticle.getTitle());
                        intent.putExtra("articleNickname", mArticle.getNickname());
                        intent.putExtra("targetId",String.valueOf(mArticle.getAuthorId()));
                        startActivity(intent);
                        break;
                    default:
                        break;

                }
                mPopTop.dismiss();
            }
        };
        conentView.findViewById(R.id.tv1).setOnClickListener(clickListener);
        conentView.findViewById(R.id.tv2).setOnClickListener(clickListener);
        tv_collection = conentView.findViewById(R.id.tv3);
        tv_collection.setOnClickListener(clickListener);
        conentView.findViewById(R.id.tv4).setOnClickListener(clickListener);

        mPopTop.setContentView(conentView);

    }

    private void initDialog(){
        mDialogShare = DialogShare.newInstance();
        mDialogShare.setOnButtonClickListener(new DialogShare.OnButtonClickListener() {
            @Override
            public void shareToWechatFriend() {
                Log.e("YYL","图片回掉");
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Bitmap bitmap = new WxShareUtil().getLocalOrNetBitmap(mShareImage);
//                                Luban.with(ArticleActivity.this)
//                                        .load(saveBitmapFile(bitmap))                                   // 传人要压缩的图片列表
//                                        .ignoreBy(100)                                  // 忽略不压缩图片的大小
//                                        .setTargetDir("/mnt/sdcard/pic/")                        // 设置压缩后文件存储位置
//                                        .setCompressListener(new OnCompressListener() { //设置回调
//                                            @Override
//                                            public void onStart() {
//                                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
//                                            }
//
//                                            @Override
//                                            public void onSuccess(File file) {
//                                                // TODO 压缩成功后调用，返回压缩后的图片文件
//                                                 Log.e("YYL","图片回掉");
//                                                Bitmap bitmap = null;
                                                WxShareUtil.getInstance().init(ArticleActivity.this).sendToWxFriend(mShareUrl, mArticalTitle, mShareImage);
//                                            }
//
//                                            @Override
//                                            public void onError(Throwable e) {
//                                                // TODO 当压缩过程出现问题时调用
//                                            }
//                                        }).launch();    //启动压缩
//                            }
//                        });
//                    }
//                }).start();
            }
            @Override
            public void shareToFriendCircle() {
                WxShareUtil.getInstance().init(ArticleActivity.this).sendToFriendCircle(mShareUrl, mArticalTitle, mShareImage);
            }
        });
    }


    @Override
    public void getArticleDetailSuccess(Article article) {

        mArticle = article;

        mArticalTitle = article.getTitle() ;
        mShareUrl = article.getArticleURL() ;
        mShareImage = article.getCover() ;
        Glide.with(this).load(article.getHeadimg()).into(ivTitleHead);

        tvNickName.setText(article.getNickname());

        if (article.isThumbsUp()) {
            Glide.with(this).load(R.drawable.heart_bottom_red).into(ivLike);
        } else {
            Glide.with(this).load(R.drawable.heart_bottom).into(ivLike);
        }

        if (article.isFollowStatus()) {
            tvFollow.setText("取消关注");
            Glide.with(this).load(R.drawable.follow_yes).into(ivFollow);
        } else {
            tvFollow.setText("关注");
            Glide.with(this).load(R.drawable.follow).into(ivFollow);
        }

        if (article.isCollectionSign()) {
            tv_collection.setText("取消收藏");
        } else {
            tv_collection.setText("收藏");
        }
        isThumbsUp = article.isThumbsUp();

        mAgentWeb = AgentWeb.with(this)//传入Activity or Fragment
                .setAgentWebParent(relativeLayout, new RelativeLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
                .setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                    @Override
                    public void onReceivedTitle(WebView view, String title) {

                    }
                }) //设置 Web 页面的 title 回调
                .createAgentWeb()
                .ready()
                .go(article.getArticleURL());
    }

    @Override
    public void articleLoveSuccess() {

        isThumbsUp = true;
        Glide.with(this).load(R.drawable.heart_bottom_red).into(ivLike);
    }

    @Override
    public void deleteArticleLoveSuccess() {
        isThumbsUp = false;
        Glide.with(this).load(R.drawable.heart_bottom).into(ivLike);
    }

    @Override
    public void articleCollectionSuccess() {
        ToastUtils.showToast(ArticleActivity.this, "收藏成功");
        tv_collection.setText("取消收藏");

    }

    @Override
    public void deleteCollectionSuccess() {
        ToastUtils.showToast(ArticleActivity.this, "取消收藏成功");
        tv_collection.setText("收藏");
    }

    @Override
    public void followChangeSuccess() {
        if (tvFollow.getText().toString().equals("关注")) {
            tvFollow.setText("取消关注");
            Glide.with(this).load(R.drawable.follow_yes).into(ivFollow);
        } else {
            tvFollow.setText("关注");
            Glide.with(this).load(R.drawable.follow).into(ivFollow);
        }
    }


    public File saveBitmapFile(Bitmap bitmap){
        File file=new File("/mnt/sdcard/pic/01.jpg");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


}
